angular.module('imsApp').controller('adContractsDetailController', ['$scope', '$rootScope', '$state', 'AdContractsManager', 'ImsAlert','$stateParams',"Lightbox","$uibModal","$filter", function ($scope, $rootScope, $state, AdContractsManager, ImsAlert,$stateParams,Lightbox, $uibModal,$filter) {
    $scope.initData = {
        "codeTable": $scope.table,
        "initCode": {
            "contractType": ["42", "43", "44"],
            "payType": ["45", "46", "47"]
        }
    };

    //更多与收起的切换
    $scope.isShow = 0;
    $scope.title={};
    $scope.home = "sky";
    $scope.changeShow = function (val) {
        $scope.isShow = val == 1 ? 0 : 1;
    };
    //拼接缩略图路径对象
    var concatUrl = function () {
        if ($scope.urlList) {
            $scope.images = [];
            for (var i = 0; i < $scope.urlList.length; i++) {
                var item = {};
                item.url = $scope.urlList[i];
                item.thumbUrl = $scope.urlList[i];
                var image = new Image();
                image.src = $scope.urlList[i];
                item.image = image;
                $scope.images.push(item);
            }
        }
    };

    //通过HASH判断是否进入新建
    if (!$stateParams.id) {
        $scope.formData = {"contractType": "42", "payType": "45"};
        $scope.planEdit = true;
    } else {
        AdContractsManager.adContractDetail($stateParams.id).then(function (result) {
            $scope.formData = result.data.adContractVO;
            $scope.title = result.data.title;
            $scope.urlList = $scope.formData.scansPathList != null ? $scope.formData.scansPathList.split(",") : [];
            concatUrl();//拼接图片对象
        })
    }

    //Listen FileNums
    $scope.$watch("uploaderImage.queue.length", function (newValue, oldValue, scope) {
        if (newValue.keywords == oldValue.keywords) {
            $scope.fileNums = $scope.uploaderImage.queue.length;
        }
    }, true);

    var image = AdContractsManager.getImage($scope);//获取文件


    $scope.submit = function () {
        if ($scope.formData.advertiserId) {
            if ($scope.checkDate()) {
                $scope.formData.scheduleStart = $filter("date")($scope.formData.scheduleStart,"yyyy-MM-dd");
                $scope.formData.scheduleEnd = $filter("date")($scope.formData.scheduleEnd,"yyyy-MM-dd");
                if($stateParams.id){
                    AdContractsManager.adContractEdit($stateParams.id,$scope.formData).then(function (result) {
                        if(result.data.c=='s'){
                            $state.reload();
                        }
                    })
                }else{
                    AdContractsManager.adContractAdd($scope.formData).then(function (result) {
                        if(result.data.c=='s'){
                            $state.go('adContracts',{},{reload:true})
                        }
                    })
                }
            }
        } else {
            alert("请选择广告主");
        }
    };

    $scope.uploadSuccess = false;
    //提交图片
    $scope.submitImage = function () {
        AdContractsManager.uploadFile($scope, image, $stateParams.id);
    };

    $scope.edit = function () {
        $scope.planEdit = true;
        //字符串日期转成对象日期
        $scope.formData.scheduleStart = new Date($scope.formData.scheduleStart);
        $scope.formData.scheduleEnd = new Date($scope.formData.scheduleEnd);
    };

    $scope.cancle = function () {
        if (!$stateParams.id) {
            $state.go("adContracts", {reload: true});
        } else {
            if ($scope.planEdit) {
                $state.reload(false);
            } else {
                $state.go("adContracts", {reload: true});
            }
        }
    };

    //model参数配置
    $scope.modelshortNameParam = {
        title: "广告主选择",
        choose: function (selectedItem) {
            $scope.title.advShortName = selectedItem.name;
            $scope.formData.advertiserId = selectedItem.id;
        }
    };

    //model 点击打开。param：title文字、body数据、选择触发回调方法，size：model大小（big、small，默认中等大小）
    $scope.modelOpen = function (param, elm, size) {
        var modal = $uibModal.open({
            templateUrl: 'myModalContent.html',
            controller: 'advertiserModalController',
            size: 'normal',
            resolve: {
                param: param
            }
        });
        modal.result.then(param.choose);
    };

    $scope.removeFile=function (index) {
        $scope.formData.scansPathList?$scope.formData.scansPathList.split(",").splice(index,1):$scope.formData.scansPathList=[];
        $scope.formData.scansPathList=$scope.formData.scansPathList.join(",")
    }

    //排期设置
    $scope.open = function (s) {
        $scope[s] = true;
    };
    var onDropComplete=function (index, obj) {
        var dragSuccess = function (result) {
            if (result.c != "s") {
                alert(result.i);
            }
        };
        //重新排序
        var idx = $scope.urlList.indexOf(obj);
        $scope.urlList.splice(idx, 1);
        $scope.urlList.splice(index, 0, obj);
        $scope.formData.scansPathList = $scope.urlList.toString();
        concatUrl();//重新拼接图片对象

      AdContractsManager.adContractSort($scope.formData.id,{scansPathList:$scope.urlList.join(",")}).then(function (result) {
          dragSuccess(result.data);
      })
    }


    /** 拖拽成功
     *    index 是将要放置的被拖拽的图片将要放置的索引位置
     *    obj 是被拖拽图片的url
     */
    $scope.onDropComplete = function (index, obj, evt) {
        onDropComplete(index, obj);
    };

    //缩略图
    $scope.openLightboxModal = function (index) {
        Lightbox.openModal($scope.images, index);
    };

    //校验合约有效期
    $scope.checkDate = function () {
        var start = $scope.formData.scheduleStart;
        var end = $scope.formData.scheduleEnd;
        if (start && end) {
            return true;
        } else {
            alert("请完成日期选择");
            return false;
        }
        ;
    };
    //校验金额
    $scope.checkPrice = function () {
        var price = $scope.formData.contractTotal;
        if (price.length == 1) {//第一位数字不能是0，只能是1到9
            $scope.formData.contractTotal = price.replace(/[^1-9]/g, '');
        } else {
            $scope.formData.contractTotal = price.replace(/\D/g, '');
        }

    }
}])

